package com.newshub.app.ui.home

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.newshub.app.R
import com.newshub.app.ui.adapter.NewsAdapter
import com.newshub.app.data.model.News
import com.newshub.app.ui.news.NewsDetailActivity

class HomeFragment : Fragment() {
    
    private lateinit var viewModel: HomeViewModel
    private lateinit var newsAdapter: NewsAdapter
    private lateinit var recyclerView: RecyclerView
    private lateinit var swipeRefresh: SwipeRefreshLayout
    
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_home, container, false)
    }
    
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        
        // 初始化视图
        recyclerView = view.findViewById(R.id.recyclerView)
        swipeRefresh = view.findViewById(R.id.swipeRefresh)
        
        setupViewModel()
        setupRecyclerView()
        setupSwipeRefresh()
        observeViewModel()
        loadNews()
    }
    
    private fun setupViewModel() {
        viewModel = ViewModelProvider(this)[HomeViewModel::class.java]
    }
    
    private fun setupRecyclerView() {
        newsAdapter = NewsAdapter(
            onItemClick = { news ->
                // 点击新闻项的处理 - 导航到新闻详情页面
                openNewsDetail(news)
            },
            onFavoriteClick = { news ->
                // 收藏/取消收藏处理
                viewModel.toggleFavorite(news)
            }
        )
        
        recyclerView.layoutManager = LinearLayoutManager(context)
        recyclerView.adapter = newsAdapter
    }
    
    private fun setupSwipeRefresh() {
        swipeRefresh.setOnRefreshListener {
            loadNews()
        }
    }
    
    private fun observeViewModel() {
        viewModel.newsList.observe(viewLifecycleOwner, { newsList ->
            newsAdapter.submitList(newsList)
            swipeRefresh.isRefreshing = false
        })
        
        viewModel.isLoading.observe(viewLifecycleOwner, { isLoading ->
            swipeRefresh.isRefreshing = isLoading
        })
        
        viewModel.error.observe(viewLifecycleOwner, { error ->
            // 显示错误信息
            if (error != null) {
                Toast.makeText(context, error, Toast.LENGTH_SHORT).show()
            }
            swipeRefresh.isRefreshing = false
        })
    }
    
    private fun loadNews() {
        viewModel.loadHeadlineNews()
    }
    
    private fun openNewsDetail(news: News) {
        try {
            // 记录详细的日志信息
            Log.d("HomeFragment", "启动NewsDetailActivity")
            Log.d("HomeFragment", "应用包名: ${requireContext().packageName}")
            Log.d("HomeFragment", "NewsDetailActivity类名: ${NewsDetailActivity::class.java.name}")
            Log.d("HomeFragment", "新闻ID: ${news.docid}")
            
            // 使用显式的类引用创建Intent
            val intent = Intent(requireContext(), NewsDetailActivity::class.java)
            intent.putExtra("news_id", news.docid)
            
            // 确保Activity存在并可启动
            val resolveInfo = requireContext().packageManager.resolveActivity(intent, 0)
            if (resolveInfo != null) {
                Log.d("HomeFragment", "成功解析Activity: ${resolveInfo.activityInfo.name}")
                startActivity(intent)
            } else {
                Log.e("HomeFragment", "无法解析Activity，可能未在AndroidManifest中声明")
                Toast.makeText(context, "无法启动新闻详情页面", Toast.LENGTH_SHORT).show()
            }
        } catch (e: Exception) {
            Log.e("HomeFragment", "启动NewsDetailActivity失败", e)
            Toast.makeText(context, "启动失败: ${e.message}", Toast.LENGTH_SHORT).show()
        }
    }
}